<?php

namespace App\Http\Controllers\ShopAdmin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Order;
use App\Models\User;
use App\Models\Shop;
use App\Models\Goods;
use App\Models\OrderGoods;
use App\Models\PushTarrif;

use App\Interfaces\OrderService;

use App\Commands\OperationLogCommand;

use Excel;
use Auth,Log,Session;

class OrderController extends Controller
{

    private $shop_id;

    /**
     * 构造函数
     */
    public function __construct()
    {

        $this->shop_id = Session::get('userShopId');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,User $user,Shop $shop)
    {

        $query =  Order::where('shop_id', $this->shop_id)->orderBy('add_time','desc');

        $filter = [

            'order_type' => $request->get('order_type'),

            'order_sn' => $request->get('order_sn'),

            'consignee'=>$request->get('consignee'),

            'mobile'=>$request->get('mobile'),

            'order_price'=>$request->get('order_price'),

            'order_status'=>$request->get('order_status'),

            'time'=>$request->get('time'),
        ];


        //订单类型

        if ($filter['order_type']&&$filter['order_type']!='ALL'){

            if ($filter['order_type']=='E') $orderType = 1;

            if ($filter['order_type']=='C') $orderType = 0;

            $query = $query->where('order_type',$orderType);
        }


        //订单号搜索

        if ($filter['order_sn']!=''){

            $query = $query->where('order.order_sn',trim($filter['order_sn']));
        }


        //收货人搜索

        if ($filter['consignee']!=''){

            $query = $query->where('order.consignee','like',"%".$filter['consignee']."%");
        }


        //收货人电话搜索

        if ($filter['mobile']!=''){

            $query = $query->where('order.mobile','like',"%".trim($filter['mobile'])."%");
        }


        //订单价格搜索

        if ($filter['order_price']!=''&& $filter['order_price']!='All'){

            $order_price = explode('-',$filter['order_price']);

            if($order_price[1]){

                $query = $query->where('order.order_price','>=',$order_price[0]);

                $query = $query->where('order.order_price','<=',$order_price[1]);
            }else{

                $query = $query->where('order.order_price','>=',$order_price[0]);
            }
        }


        //订单状态

        if ($filter['order_status']&&$filter['order_status']!='ALL'){

            $query = $query->where('order.order_status',$filter['order_status']);
        }

        //时间

        if ($filter['time']&&$filter['time']!='ALL'){

            $time = explode('|',$filter['time']);

            $query = $query->where('order.add_time','>=',$time[0]);

            $query = $query->where('order.add_time','<=',$time[1]);
        }


        //订单状态：1:待支付; 2:待发货；3:已发货；4:已完成；5:已取消；

        $orderStatusArr = ['0'=>'状态', '1'=>'待支付','2'=>'待发货','3'=>'已发货','4'=>'已完成','5'=>'已取消'];

        //如果是导出excel

        if ($request->get('export')==1){

            return $this->export($query);
        }

        $downloadUrl = $request->fullUrl();

        if (strpos($downloadUrl,'?')==true){

            $downloadUrl = $downloadUrl.'&export=1';
        }else{

            $downloadUrl = $downloadUrl.'?export=1';
        }

        $typeArr = ['0'=>'普通', '1'=>'外贸'];

        $orderInfo = $query->paginate(10);

        return view('shop_admin.order.index', compact('orderInfo', 'orderStatusArr', 'user', 'filter', 'shopsArr', 'downloadUrl', 'typeArr'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id,OrderService $orderService, User $user, Shop $shop, Goods $goods_detail, Request $request)
    {
        $back_url = '';

        if($request->back_url){

            $back_url = $request->back_url;
        }


        $order = $orderService->getByOrderId($id);

        $userInfo = '';

        if($order->user_id){

            $userInfo = User::findOrNew($order->user_id);
        }


        $shippingList = config('shipping');

        foreach($shippingList as $k=>$v){

            $shippingList[$k] = $v['name'];
        }

        $pushTarrif = PushTarrif::where('order_id', $id)->first();

        return view('shop_admin.order.detail', compact(['order', 'user', 'shippingList', 'shop', 'goods_detail', 'userInfo', 'back_url', 'pushTarrif']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    /**
     * 导出EXCEL
     * @param  [type] $query [description]
     * @return [type]        [description]
     */
    public function export($query){

        $year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');

        $fileName = $year_code[intval(date('Y')) - 2010] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('d', rand(0, 99));

        $title = array('订单编号', '运单号', '订单状态', '商品类型', '商铺名称', '订单时间', '商品条形码', '商品货号', '商品名称', '商品价格', '运费', '税费', '销售总价', '优惠券金额', '折扣金额', '买家实际支付金额', '支付类型', '商品数量', '收货人姓名', '身份证号', '联系电话', '所在省', '所在市', '所在区', '详细地址', '备注', '订单备录');


        $data = $query->get();

        Excel::create($fileName, function ($excel) use ($data, $title) {

            $excel->setTitle('订单详情');

            $excel->setCreator('阿福易购')->setCompany('阿福易购');

            $excel->sheet("订单详情", function ($sheet) use ($data, $title) {

                $sheet->freezeFirstRow();

                $sheet->setAutoSize(true);

                $sheet->row(1, $title);

                $arrayList = array();

                $orderStatusArr = ['0'=>'状态', '1'=>'待支付','2'=>'待发货','3'=>'已发货','4'=>'已完成','5'=>'已取消','6'=>'已退款'];

                // Set width for multiple cells
                $sheet->setWidth(array(
                    'A'     =>  20,
                    'B'     =>  30,
                    'C'     =>  10,
                    'D'     =>  10,
                    'E'     =>  10,
                    'F'     =>  20,
                    'G'     =>  20,
                    'H'     =>  35,
                    'I'     =>  35,
                    'J'     =>  10,
                    'K'     =>  10,
                    'L'     =>  10,
                    'M'     =>  10,
                    'N'     =>  10,
                    'O'     =>  10,
                    'P'     =>  10,
                    'Q'     =>  20,
                    'R'     =>  12,
                    'S'     =>  12,
                    'T'     =>  20,
                    'U'     =>  15,
                    'V'     =>  20,
                    'W'     =>  20,
                    'X'     =>  20,
                    'Y'     =>  35,
                    'Z'     =>  20,
                    'AA'    =>  40
                ));

                foreach ($data as $order) {

                    $orderGoods = OrderGoods::select('order_goods.*', 'goods.goods_bar_code', 'order.order_status')

                        ->join('goods', 'goods.goods_id', '=', 'order_goods.goods_id')

                        ->join('order', 'order.order_id', '=', 'order_goods.order_id')

                        ->where('order.order_id', $order->order_id)

                        ->get();


                    $shop = Shop::find($order->shop_id);

                    $shop_name = '';

                    if ($shop) {

                        $shop_name = $shop->shop_name;
                    }

                    switch ($order->pay_type) {

                        case 'alipay':
                            $pay_type = '支付宝';
                            break;

                        case 'wxpay':
                            $pay_type = '微信';
                            break;

                        case 'pinganpay':
                            $pay_type = '平安银行';
                            break;

                        default:
                            $pay_type = '';
                            break;
                    }

                    foreach($orderGoods as $good){

                        $order_type = empty($order->order_type) ? '免税' : 'e贸易';

                        $goods_price = $good->shop_price;

                        if (isset($good->goods_real_price) && $good->goods_real_price>0) {
                            $goods_price = $good->goods_real_price;
                        }

                        $arrayList[] = array($order->order_sn,$order->shipping_num.' ',$orderStatusArr[$order->order_status], $order_type, $shop_name, $order->add_time, $good->goods_bar_code, $good->goods_sn, $good->goods_name, $goods_price, $order->shipping_fee, $order->order_tariff_fee, $order->order_price, $order->coupon_price, $order->discount_price, $order->pay_price, $pay_type, $good->buy_number, $order->consignee, $order->id_card.' ', $order->mobile, $order->province, $order->city, $order->district, $order->address, $order->shipping_message, $order->order_record);
                    }

                }

                $sheet->rows($arrayList);
            });
        })->export('xls');  //storage_path('excel')
    }


    /**
     * 订单详情
     *
     * @date 2016/06/01
     * @author Leen
     */
    public function detail($order_identification, OrderService $orderService){

        if(intval($order_identification)>0){

            $orderInfo = $orderService->getByOrderId($order_identification);
        }else{

            $orderInfo = $orderService->getByOrderSn($order_identification);
        }

        $orderInfo = $orderInfo->toArray()[0];

        return view('shop_admin.order.detail', compact('orderInfo'));
    }
}
